package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailAddTeamGroupDTO;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailChangeMainDTO;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailCoAddDTO;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailCoDelDTO;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailDTO;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailDisbandTeamDTO;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailEditLabelDTO;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailMainAddDTO;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailMainDelDTO;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailRenameDTO;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailUpdateDTO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailAddTeamGroupVO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailChangeMainVO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailCoAddVO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailCoDelVO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailDisbandTeamVO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailEditCoPerVO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailEditLabelVO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailMainAddVO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailMainDelVO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailRenameVO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailVO;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.service.TeamDetailService;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author: 汪腾伟
 * @date: Created in 2021/12/23 16:09
 * @description： 详情团队控制类
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/tab/team")
public class TabTeamController {

    @Resource
    private TeamDetailService teamDetailService;
    @Resource
    private PaasRedisHelper paasRedisHelper;

    /**
     * 详情页的团队信息
     *
     * @param teamDetailDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/detail", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String teamDetail(@RequestBody @Valid TeamDetailDTO teamDetailDTO, BindingResult br) {
        XbbResponse<TeamDetailVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TransmittableThreadLocalUtil.setValue(teamDetailDTO.getSaasMark(),teamDetailDTO.getBusinessType(), teamDetailDTO.getMenuId(), teamDetailDTO.getDistributorMark());
                TeamDetailVO object = teamDetailService.teamDetail(teamDetailDTO);
                response = new XbbResponse<>(object);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }


    /**
     * 团队成员详情页修改协同人权限
     *
     * @param teamDetailUpdateDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/editCoPermission", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String editCoPermission(@RequestBody @Valid TeamDetailUpdateDTO teamDetailUpdateDTO, BindingResult br) {
        XbbResponse<Object> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TeamDetailEditCoPerVO teamDetailEditCoPerVO = teamDetailService.editCoPermission(teamDetailUpdateDTO);
                response = new XbbResponse<>(teamDetailEditCoPerVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }


    /**
     * 解散团队
     * （1）团队解散后所有人员全部移除
     * （2）必须保留一个负责团队，最后一个团队无法解散，提示“团队解散失败，失败原因：必须保留一个团队”
     *
     * @param teamDetailDisbandTeamDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/disbandTeam", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String disbandTeam(@RequestBody @Valid TeamDetailDisbandTeamDTO teamDetailDisbandTeamDTO, BindingResult br) {
        XbbResponse<Object> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TeamDetailDisbandTeamVO teamDetailDisbandTeamVO = teamDetailService.disbandTeam(teamDetailDisbandTeamDTO);
                response = new XbbResponse<>(teamDetailDisbandTeamVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 修改团队名称
     *
     * @param teamDetailRenameDTO 修改团队名称（隔离）入参
     * @param br
     * @return
     */
    @RequestMapping(value = "/renameTeam", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String renameTeam(@RequestBody @Valid TeamDetailRenameDTO teamDetailRenameDTO, BindingResult br) {
        XbbResponse<Object> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TeamDetailRenameVO teamDetailDisbandTeamVO = teamDetailService.renameTeam(teamDetailRenameDTO);
                response = new XbbResponse<>(teamDetailDisbandTeamVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }


    /**
     * 编辑团队里面的成员标签
     *
     * @param teamDetailEditLabelDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/editLabel", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String editLabel(@RequestBody @Valid TeamDetailEditLabelDTO teamDetailEditLabelDTO, BindingResult br) {
        XbbResponse<Object> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                // 判断是否跳过重复提交校验
                if (!Boolean.TRUE.equals(teamDetailEditLabelDTO.getIgnoreConCheck())) {
                    //重复提交校验
                    if (!paasRedisHelper.checkConcurrentLock(teamDetailEditLabelDTO)) {
                        response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                        return JSON.toJSONString(response);
                    }
                }
                TeamDetailEditLabelVO teamDetailEditLabelVO = teamDetailService.editLabel(teamDetailEditLabelDTO);
                response = new XbbResponse<>(teamDetailEditLabelVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 团队详情新增团队
     *
     * @param teamDetailAddTeamGroupDTO 团队详情新增团队接收实体（隔离模式）
     * @param br
     * @return
     */
    @RequestMapping(value = "/addTeamGroup", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addTeamGroup(@RequestBody @Valid TeamDetailAddTeamGroupDTO teamDetailAddTeamGroupDTO, BindingResult br) {
        XbbResponse<Object> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TeamDetailAddTeamGroupVO teamDetailAddTeamGroupVO = teamDetailService.addTeamGroup(teamDetailAddTeamGroupDTO);
                response = new XbbResponse<>(teamDetailAddTeamGroupVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }


    /**
     * 负责人新增（目前只存在共享模式下）
     *
     * @param teamDetailMainAddDTO 团队详情新增团队接收实体（共享模式）
     * @param br
     * @return
     */
    @RequestMapping(value = "/mainAdd", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String mainAdd(@RequestBody @Valid TeamDetailMainAddDTO teamDetailMainAddDTO, BindingResult br) {
        XbbResponse<Object> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TeamDetailMainAddVO teamDetailMainAddVO = teamDetailService.mainAdd(teamDetailMainAddDTO);
                response = new XbbResponse<>(teamDetailMainAddVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }


    /**
     * 替换负责人（共享/隔离）
     *
     * @param teamDetailChangeMainDTO 替换负责人接收实体
     * @param br
     * @return
     */
    @RequestMapping(value = "/changeMain", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String changeMain(@RequestBody @Valid TeamDetailChangeMainDTO teamDetailChangeMainDTO, BindingResult br) {
        XbbResponse<Object> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TeamDetailChangeMainVO teamDetailChangeMainVO = teamDetailService.changeMain(teamDetailChangeMainDTO);
                response = new XbbResponse<>(teamDetailChangeMainVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 删除负责人（共享模式）
     *
     * @param teamDetailMainDelDTO 替换负责人接收实体
     * @param br
     * @return
     */
    @RequestMapping(value = "/mainDel", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String mainDel(@RequestBody @Valid TeamDetailMainDelDTO teamDetailMainDelDTO, BindingResult br) {
        XbbResponse<Object> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TeamDetailMainDelVO teamDetailMainDelVO = teamDetailService.mainDel(teamDetailMainDelDTO);
                response = new XbbResponse<>(teamDetailMainDelVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }


    /**
     * 删除协同人
     *
     * @param teamDetailCoDelDTO 删除协同人接收实体
     * @param br
     * @return
     */
    @RequestMapping(value = "/coDel", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String coDel(@RequestBody @Valid TeamDetailCoDelDTO teamDetailCoDelDTO, BindingResult br) {
        XbbResponse<Object> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TeamDetailCoDelVO teamDetailCoDelVO = teamDetailService.coDel(teamDetailCoDelDTO);
                response = new XbbResponse<>(teamDetailCoDelVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 新增协同人
     *
     * @param teamDetailCoAddDTO 删除协同人接收实体
     * @param br
     * @return
     */
    @RequestMapping(value = "/coAdd", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String coAdd(@RequestBody @Valid TeamDetailCoAddDTO teamDetailCoAddDTO, BindingResult br) {
        XbbResponse<Object> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TeamDetailCoAddVO teamDetailCoAddVO = teamDetailService.coAdd(teamDetailCoAddDTO);
                response = new XbbResponse<>(teamDetailCoAddVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

}
